package com.ciaojian.worker.controller;

import com.ciaojian.core.util.LogUtil;
import com.ciaojian.core.util.Result;
import com.ciaojian.miniapp.api.WxMiniAppApi;
import com.ciaojian.miniapp.model.request.Code2Session;
import com.ciaojian.miniapp.model.response.Code2SessionResponse;
import com.ciaojian.worker.service.WorkerServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Atlakyn
 */
@Api(tags = "登录")
@RequestMapping("/login")
@RestController
public class LoginController {
    @Resource
    private WorkerServiceImpl workerService;

    @Value("${wx-access-token.appid}")
    private String appid;
    @Value("${wx-access-token.secret}")
    private String secret;

    @ApiOperation("发型师登录")
    @PostMapping
    public Result login(@ApiParam(value = "手机号", required = true) String phone, String openId) {
        Assert.hasText(phone, "请输入手机号");
        Assert.hasText(openId, "openId不能为空");
        return Result.ok(workerService.login(phone, openId));
    }

    /**
     * 通过code获取openid
     */
    @ApiOperation("获取 openid")
    @GetMapping("userOpenId")
    public Result userOpenId(@ApiParam("发型师端获取的code") String code) {
        Assert.hasText(code, "code不能为空");

        Code2Session code2Session = Code2Session.builder()
                .appid(appid)
                .secret(secret)
                .js_code(code)
                .build();
        try {

            Code2SessionResponse response = WxMiniAppApi.code2Session(code2Session, Code2SessionResponse.class);
            return Result.ok(response);
        } catch (Exception e) {
            LogUtil.writeBusinessErrorLog(e, "code2Session = {}", code2Session);
            return Result.error("系统异常");
        }
    }
}
